#!/bin/bash
#
# manage universe

info() {
    content=$1
    case "$decorator" in
    pure)
        echo "[$content]"
    ;;
    *)
        echo -e "\E[32;40m[$content]\033[0m"
    ;;
    esac
}

warn() {
    content=$1
    case "$decorator" in
    pure)
        echo "[$content]"
    ;;
    *)
        echo -e "\E[31;40m[$content]\033[0m"
    ;;
    esac
}

prog="node"
options="--max-old-space-size=4000" #设置nodejs内测限制M

RETVAL=0
_start() {
    name=$1
    args=$2
    logs=$3
    pidfile="$1.pid"

    echo -n $"Starting $name "
    if [ -f $pidfile ]; then
        warn "FAIL"
        echo "$name is Running"
    else
        nohup $prog $args >>$logs 2>>$logs &
        for i in {1..20}; do
            if [ -f $pidfile ]; then
                info "OK"
                break
            else
                if [ $i -eq 20 ]; then
                    warn "FAIL"
                fi
            fi
            sleep 1
        done
    fi
    RETVAL=$?
}

_stop() {
    name=$1
    pidfile="$1.pid"

    echo -n $"Stopping $name "
    if [ -f ${pidfile} ]; then
        pid=`cat ${pidfile}`
        if [ -d "/proc/${pid}" ]; then
            while [ -d "/proc/${pid}" ]; do
                kill  ${pid}
                sleep 1
            done
        fi
        rm -f ${pidfile}
    fi
    info "OK"
    RETVAL=$?
}

_reload() {
    echo $"Reloading nothing "
    RETVAL=$?
}

_status() {
    name=$1
    pidfile="$1.pid"
    
    echo -n -e "$name "
    if [ -f ${pidfile} ]; then
        pid=`cat ${pidfile}`
        if [ -d "/proc/${pid}" ]; then
            info "Running"
        else
            warn "Lost"
        fi
    else
        warn "Stoped"
    fi

    RETVAL=$?
}

start() {
    config='config.js'
    if [ -f '../config.js' ]; then
        config='../config.js'
    fi

    serverId=`grep exports.ServerId $config| awk '{print $3}' | awk -F';' '{print $1}'`

    _start universe universe.js log/universe_manage.log
    
    pidfile='alarm.pid'
    echo -n $"Starting alarm "
    if [ -f $pidfile ]; then
        warn "FAIL"
        echo "alarm is Running"
    else
        ./universe_alarm $serverId >/dev/null &
        info "OK"
    fi
}

stop() {
    _stop alarm
    _stop universe
}

status() {
    _status universe
    _status alarm
}

# See how we were called.
cmd=$1
decorator="default"
if [ ${cmd:0:5} == "pure." ]; then
    decorator="pure"
    cmd=${cmd:5}
fi

case "$cmd" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status
        ;;
  restart)
        stop
        sleep 3
        start
        ;;
  reload)
        _reload
        ;;
  *)
        echo $"Usage: manage {start|stop|restart|status|reload}"
        exit 1
esac

exit $RETVAL
